'use strict';

module.exports = app => {
  const { STRING, DATE } = app.Sequelize;

  const RefreshToken = app.model.define('refreshToken', {
    refreshToken         : { type: STRING, unique: true },
    refreshTokenExpiresAt: DATE,
    scope                : STRING,
    clientId             : STRING,
    userId               : { type: STRING, allowNull: false },
  }, {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
    tableName: 'zconnect-refresh-token',
  });

  // 保存refreshToken
  RefreshToken.saveRefreshToken = async function(token, client, user) {
    await this.create({
      refreshToken         : token.refreshToken,
      refreshTokenExpiresAt: token.refreshTokenExpiresAt,
      clientId             : client.clientId,
      userId               : user.lid,
      scope                : token.scope || '',
    });
  };

  // 删除refreshToken
  RefreshToken.delRefreshToken = async function(token) {
    return await this.destroy({
      where: {
        refreshToken: token.refreshToken,
      },
    });
  };

  // 搜索refreshToken
  RefreshToken.queryRefreshToken = async function(refreshToken) {
    return await this.findOne({
      where: {
        refreshToken,
      },
    });
  };

  return RefreshToken;
};
